# -*- coding: utf-8 -*-
#!/usr/bin/env python
#This script is designed to download and extract a particular atmosphere file for use in MOOG, it will then use this atmosphere model in MOOG and then plot the output in gnuplot

import sys, glob, urllib, re, os, shutil, math, param_finder_modules

def modelmaker_atmosphy(resolution, wavels, wavelf, temp,gravity,FeH):
	abundance=0.5
	synspec=glob.glob("/home/jeffrey/PHD/isooctane/data/synspec/res%(res)s/%(s)s_%(f)s/t%(temp)03dg%(grav)1.2fm%(FeH)1.2fk2.00a0.00Ba%(abundance)1.1f.spec" \
		% {"res": resolution,"s": wavels, "f":wavelf, "temp": temp, "grav": gravity, "FeH": FeH, "abundance":abundance})
	if synspec==[]:
		modelatmos=glob.glob("/home/jeffrey/PHD/isooctane/data/modelatm/t%(temp)03dg%(grav)1.2fm%(FeH)1.2fk2.00a0.00.model" \
		% {"temp": temp, "grav": gravity, "FeH": FeH})
		print "/home/jeffrey/PHD/isooctane/data/modelatm/t%(temp)03dg%(grav)1.2fm%(FeH)1.2fk2.00a0.00.model" \
		% {"temp": temp, "grav": gravity, "FeH": FeH}
		if modelatmos==[]:
			os.chdir('/home/jeffrey/PHD/isooctane/data/modelatm')
			cmd='atmosphy -teff '+str(temp)+' -logg '+str(gravity)+' -feh '+str(FeH)
			os.system(cmd)
		shutil.copy("/home/jeffrey/PHD/isooctane/data/modelatm/t%(temp)03dg%(grav)1.2fm%(FeH)1.2fk2.00a0.00.model" \
		% {"temp": temp, "grav": gravity, "FeH": FeH}, "/home/jeffrey/PHD/software/MOOG2010/model_atm/kurucz")
		for abundance in (0.0, 0.5, 1.0):
			batchfilemaker(wavels, wavelf, abundance, resolution)
			param_finder_modules.moogmodelcreator_atmosphy(temp,gravity,FeH,abundance,resolution,wavels,wavelf)

def modelmaker(metallicity, FeH, temp, gravity):
    #Looks to see if the Kurucz model files for these parameters has been downloaded already, if not, it downloads it. Needs to deal with metallicities greater than -1.0 and adds an extra 0 for them
    os.chdir('/home/jeffrey/PHD/isooctane/data/kurucz_models')
    if FeH>-0.76:
      filelist = glob.glob('am0'+metallicity+'k2.dat')
    else:
      filelist = glob.glob('am'+metallicity+'k2.dat')
    if filelist==[]:
        try:
	    print "Do not have the Kurucz grid of models. I will download it for you."
	    if FeH>-0.76:
	      URL= 'http://kurucz.harvard.edu/grids/gridm0'+ metallicity+'/am0'+metallicity+'k2.dat'
              urllib.urlretrieve(URL, 'am0'+metallicity+'k2.dat')
              modelatmfile = open('am0'+metallicity+'k2.dat', 'r')
            else:
	      URL= 'http://kurucz.harvard.edu/grids/gridm'+ metallicity+'/am'+metallicity+'k2.dat'
              urllib.urlretrieve(URL, 'am'+metallicity+'k2.dat')
              modelatmfile = open('am'+metallicity+'k2.dat', 'r')
        except (IOError):
	  print metallicity
	  print FeH
	  print "Could not find model that matched this given metallicity"; sys.exit(1)
    else:
      if FeH>-0.76:
        modelatmfile = open('am0'+metallicity+'k2.dat', 'r')
      else:
        modelatmfile = open('am'+metallicity+'k2.dat', 'r')

    #Deletes any previous file
    if glob.glob('/home/jeffrey/PHD/software/MOOG2010/model_atm/kurucz')!=[]:
        os.remove('/home/jeffrey/PHD/software/MOOG2010/model_atm/kurucz')
    if glob.glob('/home/jeffrey/PHD/software/MOOG2010/out3')!=[]:
        os.remove('/home/jeffrey/PHD/software/MOOG2010/out3')

    #ofile=open('kurucz_'+temp+'_'+gravity+'_'+metallicity, 'w')
    ofile=open('/home/jeffrey/PHD/software/MOOG2010/model_atm/kurucz', 'w')

    #Extracts the particular section of the Kurucz file that matches the parameters in the input
    pattern1 =r'EFF.*'+str(temp)+'.*GRAVITY\s{1}'+str(gravity)+'.*'
    pattern2 =r'EAD DECK6 (\d+)' #It is like this since in the Kurucz grid some of the models have 72 or 64 depths
    pattern3 =r'RADK.*'
    trigger_line=False
    trigger=False
    for line in modelatmfile:
        match3 = re.search(pattern3, line)
        if match3 and trigger_line:
            break
        if trigger_line==True:
            ofile.write(line)
        match1 = re.search(pattern1, line)
        if match1:
            trigger=True
        match2 = re.search(pattern2, line)
        if match2 and trigger==True:
            tau=match2.group(1)
            ofile.write('KURUCZ\nno-oversht '+str(temp)+' '+str(gravity)+' '+str(-1*float(metallicity)/10)+' 2.00\nntau         '+tau+'\n')
            trigger_line=True

    #Exits the script if it gets to the end of the grid without writing out anything
    if trigger==False and trigger_line==False:
        print str(temp)+' '+str(gravity)+' '+str(-1*float(metallicity)/10)
        print 'input parameters did not match any of the models available'; sys.exit(1)

    #Adds the abundances information at the bottom of the file
    ofile.write("     2.00e+05\n") #Microturbulence value
    ofile.write("natoms        0     "+str(-1*float(metallicity)/10))
    ofile.write("""
nmol         17
      101.      106.      107.      108.      606.      607.      608.
      707.      708.      808.    10108.    60808.      12.1      112. 
      114.      812.      822.""")
    ofile.close()

def batchfilemaker(wavels, wavelf, abundance, resolution):
    #Create the moog parameter file based on the wavelength inputs at the top
    os.chdir('/home/jeffrey/PHD/software/MOOG2010')
    ofile = open ('batch.par','w')
    ofile.write("""synth
terminal       'x11'
standard_out   'out1'
summary_out    'out2'
smoothed_out   'out3'
model_in       'model_atm/kurucz'
stronglines_in 'linelists/strongca4226'
""")
    ofile.write("lines_in       'linelists/lin"+str((int(wavels)/100)*100)+"'\n") #Selects the correct linelist
    ofile.write("""atmosphere    1
molecules     1
lines         1
flux/int      1
damping       0
plot          1
freeform      0
strong        1
abundances    1   1
       56   """)
    ofile.write(str(abundance)+"\n")
    ofile.write("synlimits\n")
    ofile.write("  "+wavels+"  "+wavelf+"    0.01    1.00\n")
    ofile.write("plotpars      1  \n")
    ofile.write("  "+wavels+"  "+wavelf+"   0.00    1.005\n")
    ofile.write("     0.0   0.000   0.000    1.00\n")
    ofile.write("   g        "+resolution+"     0.00    0.00    0.00    0.00\n")
    ofile.write("obspectrum    5")
    ofile.close()
    
#isotopes      5   1
  #56.1134 41.67
  #56.1135 15.15
  #56.1136 12.66
  #56.1137 8.85
  #56.1138 1.39

def cutandmove(temp,gravity,FeH,resolution,wavels,wavelf,abundance):
    moogdir='/home/jeffrey/PHD/software/MOOG2010'
    os.chdir(moogdir)
    #Cuts the first two lines from the MOOG output file which are just comments
    readFile=open('out3')
    lines = readFile.readlines()
    readFile.close()
    w = open("out3cut",'w')
    w.writelines([item for item in lines[2:]])
    w.close()
    shutil.copy('out3cut', "/home/jeffrey/PHD/isooctane/data/synspec/res%(res)s/%(s)s_%(f)s/t%(temp)03dg%(grav)1.2fm%(FeH)1.2fk2.00a0.00Ba%(abundance)1.1f.spec" \
		% {"res": resolution,"s": wavels, "f":wavelf, "temp": temp, "grav": gravity, "FeH": FeH, "abundance":abundance})
    
